/* eslint-disable valid-jsdoc */
const router = require('../config/router');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const secret = 'bbsGouLiZhi*@!***';
function author() {
    /**
    * 验证
    * @type {function(): Function}
    */
    return async (ctx, next) => {
        const url = verifyRoute(ctx.request.url);
        if (url) {
            await next();
        } else {
            let token = ctx.header.token;

            if (!token) {
                token = ctx.request.query.token;
                if (!token) {
                    ctx.errors('The token was not found');
                    return;
                }
            }
            /**
             * 验证token
             * @type {*}
             */
            let data = verifyToken(token);

            if (!data) {
                ctx.body = { code: 2, msg: '信息已经失效' };
                return;
            }
            /** 赋值user*/
            ctx.user = data;
            await next();
        }
    };
}
/**
 * 验证token
 * @param _token
 * @returns {*}
 */
function verifyToken(_token) {
    let verify = jwt.verify(_token, secret, (error, decoded) => {
        if (error) {
            return false;
        }
        return decoded;
    });
    return verify;
}
/**
 * 过滤白名单
 * @type {function(): Function}
 */
function verifyRoute(url) {
    const status = _.includes(router, url);
    return status;
}
module.exports = author;
